<?php

namespace app\cash\model;

use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\GoodsSkuModel;
use app\common\model\CommonModel;
use app\stores\model\order\ReasonModel;
use think\facade\Db;


class CartModel extends CommonModel{

    protected  $name = 'beautiful_cart';

    protected  $pk   = 'cart_id';
    /**
     * 模型写入前事件（钩子函数）
     */
    public static function onBeforeInsert($model)
    {
        $model->set("add_time", date('Y-m-d H:i:s'));
        $model->set("add_ip", request()->ip());
    }
    public static function num($where)
    {
        $count = self::where($where)->sum('num');
        return $count;
    }
    public static function getCart($where)
    {
        $list = self::where($where)->find();
        if($list) $list = $list->toArray();
        return $list;
    }

    public static function up($data,$where)
    {
        return self::update($data,$where);
    }

    public static function getCashCartList($member,$where,$order=[],$page=0,$limit=0,$field='*'){
        $query =  Db::name('beautiful_cart')->alias('c')
            ->join('beautiful_goods g','c.goods_id=g.goods_id')
            ->join('beautiful_goods_other_sku_detail d','d.other_sku_detail_id=g.unit_id')
            ->where('c.is_delete=0 or (g.is_delete=1 and  c.status>0)')
            ->when(isset($where['table_number_id']),function ($query) use ($where){
                $query->where(['c.table_number_id'=>$where['table_number_id']]);
            })
            ->when(isset($where['member_id']),function ($query) use ($where){
                $query->where(['c.member_id'=>$where['member_id']]);
            })
            ->when(isset($where['origin_type']),function ($query) use ($where){
                $query->where(['c.origin_type'=>$where['origin_type']]);
            })
            ->when(isset($where['service_type']),function ($query) use ($where){
                $query->where(['c.service_type'=>$where['service_type']]);
            })
            ->when(isset($where['is_fit']),function ($query) use ($where){
                $query->where(['c.is_fit'=>$where['is_fit']]);
            })
            ->when(isset($where['shop_id']),function ($query) use ($where){
                $query->where(['c.shop_id'=>$where['shop_id']]);
            })
            ->when(isset($where['account_id']),function ($query) use ($where){
                $query->where(['c.account_id'=>$where['account_id']]);
            })->field($field);
        $count = $query->count();
        if($page>0) $query = $query->page($page);
        if($limit>0) $query = $query->limit($limit);
        $list = $query->order($order)->select()->toArray();

        $total_num = $youhui_price = $total_price = 0;
        if(!empty($list)){
            $goodsSkuModel = new GoodsSkuModel();
            foreach ($list as $k=>$v){
                $skus = $return = [];$sku = null;
                $list[$k]['goods'] = $v['goods'] = [
                    'goods_id'=>$v['goods_id'],
                    'name'=>$v['name'],
                    'cover_img'=>$v['cover_img'],
                    'original_price'=>$v['crossed_price'],
                    'quota'=>$v['quota'],
                    'vip_discount_type'=>$v['vip_discount_type'],
                    'is_vip_discount'=>$v['is_vip_discount'],
                    'discount_detail'=>$v['discount_detail'],
                    'status'=>$v['status'],
                    'crossed_price'=>$v['crossed_price'],
                    'start_sales_num'=>$v['start_sales_num'],
                    'max_num'=>$v['max_num'],
                    'unit_name'=>$v['unit_name'],
                    'origin_type'=>$v['origin_type'],
                ];
                $hx_price = $v['crossed_price'];
                if($v['type']==3){
                    $re = CartDetailModel::list(['cart_id'=>$v['cart_id'],'is_delete'=>0],['add_time'=>'asc']);
                    $list[$k]['goods']['detail'] = $re['list'];
                }
                $v['goods']['discount_detail'] = json_decode($v['discount_detail'],true);
                $return = getMemberPrice($member,$v['shop_id'],$v['goods'],$v['crossed_price'],$v['type'],0,0,$v['num']);

                if($v['sku_id']){
                    $sku_where = [
                        'sku_id'=>$v['sku_id'],
                        'goods_id'=>$v['goods_id']
                    ];
                    $sku = $goodsSkuModel->getById($sku_where,'name,goods_id,crossed_price,discount_detail,quota,start_sales_num');
                    if($sku){
                        $sku['discount_detail'] = $sku['discount_detail'];
                        $sku['original_price'] = $sku['crossed_price'];
                        $sku['origin_type'] = $v['origin_type'];
                        $skus[] = $sku;
                        if($member){
                            $sku_return = skuMemberPrice($v['vip_discount_type'],$skus,$member,$v['shop_id'],$v['type'],$v['origin_type'],$v['num']);
                            if($sku_return){
                                $sku['price'] = sprintf("%.2f",$sku_return[0]['price']);
                                $return = $sku_return[0];
                            }
                        }else{
                            $sku['price'] = sprintf("%.2f",$sku['crossed_price']);
                            $return['price'] = $sku['price'];
                            $return['discount_info'] = NULL;
                        }
                        $hx_price = $sku['price'];
                        unset($sku['discount_detail']);
                        $list[$k]['goods']['crossed_price'] = $sku['crossed_price'];
                    }

                }
                $list[$k]['goods']['sku_name'] = $sku?$sku['name']:NULL;
                $list[$k]['total_price'] = $return['price'] * $v['num'];
                $list[$k]['discount_info'] = $return['discount_info'];
                //改价
                if($v['price']>0){
                    $list[$k]['total_price'] = $v['price'] * $v['num'];
                    $list[$k]['discount_info'] =  '改价优惠：-¥'.sprintf("%.2f",($hx_price-$v['price'])*$v['num']);
                }
                $list[$k]['un_confirm_num'] = $v['num'] - $v['confirm_num'];
                unset($list[$k]['goods']['discount_detail']);
                unset($list[$k]['name']);
                unset($list[$k]['cover_img']);
                unset($list[$k]['original_price']);
                unset($list[$k]['quota']);
                unset($list[$k]['vip_discount_type']);
                unset($list[$k]['is_vip_discount']);
                unset($list[$k]['discount_detail']);
                unset($list[$k]['status']);
                unset($list[$k]['crossed_price']);
                unset($list[$k]['start_sales_num']);
                unset($list[$k]['max_num']);
                unset($list[$k]['type']);
                $total_num+=$v['num'];
                $total_price+=$list[$k]['total_price'];
            }
        }
        return compact('count','list','total_num','youhui_price','total_price');
    }
    public static function list($where,$where_in=[]){
        $list = self::where($where)->where($where_in)->select()->toArray();
        return $list;
    }

}

